package com.project2.service;

import com.project2.bean.PageBo;
import com.project2.bean.bo.CartAddBo;
import com.project2.bean.bo.CartCheckedBo;
import com.project2.bean.bo.CartCheckoutBo;
import com.project2.bean.po.*;
import com.project2.bean.vo.CartIndexVo;
import com.project2.bean.vo.CartTotalVo;
import com.project2.mapper.*;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * TODO
 *
 * @param
 * @author wj
 * @return
 */
@Service
public class WxCartServiceImpl implements WxCartService {
    @Autowired
    MarketCartMapper marketCartMapper;
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketGrouponRulesMapper marketGrouponRulesMapper;
    @Autowired
    MarketSystemMapper marketSystemMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Override
    public CartIndexVo index(MarketUser user) {
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andUserIdEqualTo(user.getId());
        CartIndexVo cartIndexVo = new CartIndexVo();
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        if(marketCarts.size()==0){
            cartIndexVo.setCartList(new ArrayList<MarketCart>());
            CartTotalVo cartTotalVo = new CartTotalVo();
            cartTotalVo.setGoodsAmount(0);
            cartTotalVo.setGoodsCount(0);
            cartTotalVo.setCheckedGoodsCount(0);
            cartTotalVo.setCheckedGoodsAmount(0);
            cartIndexVo.setCartTotal(cartTotalVo);
            return cartIndexVo;
        }
        int count=0;
        int checkedCount=0;
        int amount=0;
        int checkedAmount=0;
        for (MarketCart marketCart : marketCarts) {
            if (marketCart.getChecked()){
                checkedCount+=marketCart.getNumber();
                checkedAmount+=checkedCount*marketCart.getPrice().intValue();
            }
            count+=marketCart.getNumber();
            amount+=count*marketCart.getPrice().intValue();
        }

        CartTotalVo cartTotalVo = new CartTotalVo();
        cartTotalVo.setGoodsAmount(amount);
        cartTotalVo.setGoodsCount(count);
        cartTotalVo.setCheckedGoodsCount(checkedCount);
        cartTotalVo.setCheckedGoodsAmount(checkedAmount);
        cartIndexVo.setCartList(marketCarts);
        cartIndexVo.setCartTotal(cartTotalVo);
        return cartIndexVo;
    }

    @Override
    public int goodsCount() {
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andDeletedEqualTo(false);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        int count=0;
        for (MarketCart marketCart : marketCarts) {
            count+=marketCart.getNumber();
        }
        return count;
    }

    @Override
    public int add(CartAddBo cartAddBo, MarketUser marketUser,boolean isFastAdd) {
        Date date = new Date();
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(cartAddBo.getGoodsId());
        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(cartAddBo.getProductId());
        if(cartAddBo.getNumber()>marketGoodsProduct.getNumber()){
           return -1;
        }

        if (isFastAdd){
            //先删除同个规格的商品
            MarketCart marketCart = new MarketCart();
            marketCart.setDeleted(true);
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria().andProductIdEqualTo(cartAddBo.getProductId());
            marketCartMapper.updateByExampleSelective(marketCart,marketCartExample);
        }
        MarketCart marketCart = new MarketCart();
        //封装一个market
        marketCart.setAddTime(date);
        marketCart.setUpdateTime(date);
        marketCart.setGoodsId(cartAddBo.getGoodsId());
        if (isFastAdd){
            marketCart.setChecked(true);
        }else {
            marketCart.setChecked(false);
        }
        marketCart.setDeleted(false);
        marketCart.setGoodsName(marketGoods.getName());
        marketCart.setGoodsSn(marketGoods.getGoodsSn());
        marketCart.setNumber(cartAddBo.getNumber().shortValue());
        marketCart.setPrice(marketGoodsProduct.getPrice());
        marketCart.setPicUrl(marketGoodsProduct.getUrl());
        marketCart.setProductId(cartAddBo.getProductId());
        marketCart.setUserId(marketUser.getId());
        marketCart.setSpecifications(marketGoodsProduct.getSpecifications());

        //判断这种规格的商品有没有，如果有，那就是修改数量，如果没有那就是新增
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andProductIdEqualTo(marketCart.getProductId());
        criteria.andUserIdEqualTo(marketCart.getUserId());
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        if (marketCarts.size()>0&&!isFastAdd){
            // 修改的逻辑：先获取当前规格的总量，然后加上这里的规格
            //计算改变之后的number
            Integer count=0;
            MarketCart marketCart1 = new MarketCart();
            // if (isFastAdd){
            //     marketCart1.setNumber(cartAddBo.getNumber().shortValue());
            // }else {
            //     for (MarketCart cart : marketCarts) {
            //         count+=cart.getNumber();
            //     }
            //     marketCart1.setNumber(count.shortValue());
            // }
            for (MarketCart cart : marketCarts) {
                count+=cart.getNumber();
            }
            marketCart1.setNumber(count.shortValue());
            int i = marketCartMapper.updateByExampleSelective(marketCart1, marketCartExample);
            return i;
        }else {
            marketCartMapper.insert(marketCart);
            int i=marketCart.getId();
            return i;
        }
    }

    @Override
    public CartIndexVo checked(CartCheckedBo cartCheckedBo) {
        CartIndexVo cartIndexVo = new CartIndexVo();
        List<Integer> productIds = cartCheckedBo.getProductIds();
        for (Integer productId : productIds) {
            //限定要修改哪些行
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andDeletedEqualTo(false);
            criteria.andProductIdEqualTo(productId);
            //设置要修改的行
            MarketCart marketCart1 = new MarketCart();
            Integer isChecked = cartCheckedBo.getIsChecked();
            if (isChecked==0){
                marketCart1.setChecked(false);
            }
            if (isChecked==1){
                marketCart1.setChecked(true);
            }
            int i = marketCartMapper.updateByExampleSelective(marketCart1, marketCartExample);
            if (i<1) {
                return null;
            }
        }
        //查询修改后的购物车信息
        MarketCartExample marketCartExample1 = new MarketCartExample();
        marketCartExample1.createCriteria().andDeletedEqualTo(false);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample1);
        int count=0;
        int checkedCount=0;
        int amount=0;
        int checkedAmount=0;
        for (MarketCart marketCart : marketCarts) {
            if (marketCart.getChecked()){
                checkedCount+=marketCart.getNumber();
                checkedAmount+=checkedCount*marketCart.getPrice().intValue();
            }
            count+=marketCart.getNumber();
            amount+=count*marketCart.getPrice().intValue();
        }

        CartTotalVo cartTotalVo = new CartTotalVo();
        cartTotalVo.setGoodsAmount(amount);
        cartTotalVo.setGoodsCount(count);
        cartTotalVo.setCheckedGoodsCount(checkedCount);
        cartTotalVo.setCheckedGoodsAmount(checkedAmount);

        cartIndexVo.setCartList(marketCarts);
        cartIndexVo.setCartTotal(cartTotalVo);
        return cartIndexVo;
    }

    @Override
    public CartIndexVo deleted(CartCheckedBo cartCheckedBo,MarketUser user) {
        // MarketUser user = (MarketUser) session.getAttribute("X-CskaoyanMarket-Token");
        List<Integer> productIds = cartCheckedBo.getProductIds();
        for (Integer productId : productIds) {
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andProductIdEqualTo(productId);
            criteria.andUserIdEqualTo(user.getId());
            MarketCart marketCart = new MarketCart();
            marketCart.setDeleted(true);
            int i = marketCartMapper.updateByExampleSelective(marketCart, marketCartExample);

            if (i==0){
                return null;
            }
        }
        //查询修改后的购物车信息
        CartIndexVo cartIndexVo = new CartIndexVo();
        MarketCartExample marketCartExample1 = new MarketCartExample();
        marketCartExample1.createCriteria().andDeletedEqualTo(false);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample1);
        int count=0;
        int checkedCount=0;
        int amount=0;
        int checkedAmount=0;
        for (MarketCart Cart : marketCarts) {
            if (Cart.getChecked()){
                checkedCount+=Cart.getNumber();
                checkedAmount+=checkedCount*Cart.getPrice().intValue();
            }
            count+=Cart.getNumber();
            amount+=count*Cart.getPrice().intValue();
        }

        CartTotalVo cartTotalVo = new CartTotalVo();
        cartTotalVo.setGoodsAmount(amount);
        cartTotalVo.setGoodsCount(count);
        cartTotalVo.setCheckedGoodsCount(checkedCount);
        cartTotalVo.setCheckedGoodsAmount(checkedAmount);

        cartIndexVo.setCartList(marketCarts);
        cartIndexVo.setCartTotal(cartTotalVo);
        return cartIndexVo;
    }

    @Override
    public int update(CartAddBo cartAddBo) {

        MarketCart marketCart = new MarketCart();
        marketCart.setNumber(cartAddBo.getNumber().shortValue());

        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andIdEqualTo(cartAddBo.getId());
        int i = marketCartMapper.updateByExampleSelective(marketCart, marketCartExample);


        return i;
    }

    @Override
    public CartCheckoutVo checkout(CartCheckoutBo cartCheckoutBo, MarketUser user) {
        CartCheckoutVo cartCheckoutVo = new CartCheckoutVo();
        Integer userId = user.getId();
        //首先根据userId找到addressId从而找到checkAddress
        MarketAddressExample marketAddressExample = new MarketAddressExample();
        MarketAddressExample.Criteria criteria = marketAddressExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andUserIdEqualTo(userId);
        if (cartCheckoutBo.getAddressId() == 0) {
            criteria.andIsDefaultEqualTo(true);
        } else {
            criteria.andIdEqualTo(cartCheckoutBo.getAddressId());
        }
        List<MarketAddress> marketAddresses = marketAddressMapper.selectByExample(marketAddressExample);
        List<MarketSystem> marketSystems = marketSystemMapper.selectByExample(null);
        MarketSystem marketSystem1 = null;
        MarketSystem marketSystem2 = null;
        for (MarketSystem marketSystem : marketSystems) {
            String keyName = marketSystem.getKeyName();
            if ("market_express_freight_min".equals(keyName)) {
                marketSystem1 = marketSystem;
            } else if ("market_express_freight_value".equals(keyName)) {
                marketSystem2 = marketSystem;
            }
        }

        MarketAddress marketAddress = marketAddresses.get(0);

        cartCheckoutVo.setAddressId(marketAddress.getId());
        cartCheckoutVo.setCheckedAddress(marketAddress);
        //再根据userId找到checkedGoodsList
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria1 = marketCartExample.createCriteria();
        criteria1.andDeletedEqualTo(false);
        criteria1.andUserIdEqualTo(userId);
        criteria1.andCheckedEqualTo(true);
        if (cartCheckoutBo.getCartId() >= 1) {
            criteria1.andIdEqualTo(cartCheckoutBo.getCartId());
        }
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        int checkedAmount = 0;
        for (MarketCart marketCart : marketCarts) {
            //判断当前数量是和大于该规格库存数量
            MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(marketCart.getProductId());
            if (marketCart.getNumber() > marketGoodsProduct.getNumber()) {
                return null;
            }
            checkedAmount += marketCart.getNumber() * marketCart.getPrice().intValue();
        }
        if (checkedAmount < Integer.valueOf(marketSystem1.getKeyValue())) {
            cartCheckoutVo.setFreightPrice(Integer.valueOf(marketSystem2.getKeyValue()));
        } else {
            cartCheckoutVo.setFreightPrice(0);
        }
        cartCheckoutVo.setGoodsTotalPrice(checkedAmount);
        //计算当前能使用的优惠券张数
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        MarketAddressExample.Criteria criteria2 = marketAddressExample.createCriteria();
        criteria2.andUserIdEqualTo(userId);
        criteria2.andDeletedEqualTo(false);
        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
        int number = 0;
        for (MarketCouponUser marketCouponUser : marketCouponUsers) {
            if (marketCouponUser.getCouponId() > 0) {
                MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(marketCouponUser.getCouponId());
                if (marketCoupon.getMin() < checkedAmount) {
                    number++;
                }
            }
        }
        cartCheckoutVo.setAvailableCouponLength(number);

        cartCheckoutVo.setCheckedGoodsList(marketCarts);
        //根据couponId找到优惠价格
        cartCheckoutVo.setCouponId(cartCheckoutBo.getCouponId());
        if (cartCheckoutBo.getCouponId() < 1) {
            cartCheckoutVo.setCouponPrice(0);
        } else {
            MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(cartCheckoutBo.getCouponId());
            cartCheckoutVo.setCouponPrice(marketCoupon.getDiscount().intValue());
        }
        cartCheckoutVo.setUserCouponId(cartCheckoutBo.getUserCouponId());
        //根据grouponRulesId找到团购优惠价格,计算订单价格
        // MarketGrouponRules marketGrouponRules = marketGrouponRulesMapper.selectByPrimaryKey(cartCheckoutBo.getGrouponRulesId());
        cartCheckoutVo.setGrouponRulesId(cartCheckoutBo.getGrouponRulesId());
        cartCheckoutVo.setGrouponPrice(0);
        int orderTotalPrice = (int) (checkedAmount + cartCheckoutVo.getFreightPrice() - cartCheckoutVo.getCouponPrice());
        cartCheckoutVo.setOrderTotalPrice(orderTotalPrice);
        cartCheckoutVo.setActualPrice(orderTotalPrice);

        return cartCheckoutVo;
    }
}
